package thread.day2;

import static java.lang.Thread.sleep;

/**
 * 实现接口的多线程方法的同步方式
 * 如果是自定义类且只一个的话，还可以用该方法
 *
 * @author wx
 * @create 2019-11-28 14:30
 */
public class SynchronizeDemo2 {

    public static void main(String[] args) {
        TicketSellClass w = new TicketSellClass();

        Thread t1 = new Thread(w);
        t1.setName("Windows-1");
        Thread t2 = new Thread(w);
        t2.setName("Windows-2");
        Thread t3 = new Thread(w);
        t3.setName("Windows-3");
        t1.start();
        t2.start();
        t3.start();
    }

}

class TicketSellClass implements Runnable {
    int ticket = 100;
    LockClass lock = new LockClass();

    @Override
    public void run() {
        //错误写法
//        int ticket = 100;
        //自定义监视器
//        synchronized (lock) {
        //高级写法(只适用于生成一个对象的情况)(注意监视器的一致)
        while (true) {
            synchronized (TicketSellClass.class) {
                if (ticket > 0) {
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " ticket： " + ticket);
                    ticket--;
                } else {
                    break;
                }
            }

        }
    }
}

class LockClass {

}
